package com.qf.fmmall.service.impl;

import com.qf.fmmall.dao.ShoppingCartMapper;
import com.qf.fmmall.entity.ShoppingCart;
import com.qf.fmmall.entity.ShoppingCartVo;
import com.qf.fmmall.service.ShoppingCartService;
import com.qf.fmmall.vo.ResStatus;
import com.qf.fmmall.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo addShopCart(ShoppingCart shoppingCart) {
        ResultVo vo = new ResultVo();
        int i = shoppingCartMapper.insert(shoppingCart);

        if (i==1){
            vo.setCode(ResStatus.OK);
            vo.setMsg("success");
        }else {
            vo.setCode(ResStatus.NO);
            vo.setMsg("添加购物车失败");
        }

        return vo;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ResultVo listByUserId(Integer userId) {
        ResultVo vo = new ResultVo();

        List<ShoppingCartVo> shoppingCartVoList=shoppingCartMapper.listByUserId(userId);
        if (shoppingCartVoList.size()==0){
            vo.setCode(ResStatus.NO);
            vo.setMsg("没有查到购物车信息");
        }else {
            vo.setCode(ResStatus.OK);
            vo.setMsg("success");
            vo.setData(shoppingCartVoList);
        }

        return vo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo update(Integer cid, Integer cnum) {
        ResultVo vo = new ResultVo();

        int i=shoppingCartMapper.updateByCid(cid,cnum);

        if (i==1){
            vo.setCode(ResStatus.OK);
            vo.setMsg("success");
        }else {
            vo.setCode(ResStatus.NO);
            vo.setMsg("更改购物车数量失败");
        }
        return vo;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ResultVo listbycids(String cids) {
        ResultVo vo = new ResultVo();
        //处理逗号分隔的字符串 cids-->11,12
        String[] split = cids.split(",");
        List<String> cidsList = Arrays.asList(split);

        List<ShoppingCartVo> shoppingCartVoList=shoppingCartMapper.listbycids(cidsList);

        if (shoppingCartVoList.size()==0){
            vo.setCode(ResStatus.NO);
            vo.setMsg("没有查到购物车信息");
        }else {
            vo.setCode(ResStatus.OK);
            vo.setMsg("success");
            vo.setData(shoppingCartVoList);
        }

        return vo;
    }
}
